﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneAppCheckSensors
{
    public partial class PageSendData : PhoneApplicationPage
    {
        public PageSendData()
        {
            InitializeComponent();
        }

        private bool fromSensorPage = true;
        private const string emailAddressKey = "email-address";
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (fromSensorPage)
            {
                var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                if (!appSettings.Contains(emailAddressKey))
                {
                    appSettings.Add(emailAddressKey, "");
                }
                tbEMailAddress.Text = appSettings[emailAddressKey] as string;

                if (NavigationContext.QueryString.TryGetValue("datafile", out fileUrl))
                {
                    try
                    {
                        var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                        using (var stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileUrl, System.IO.FileMode.Open, storage))
                        {
                            var reader = new System.IO.StreamReader(stream);
                            tbContent.Text = reader.ReadToEnd();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed to get sensor data! : " + ex.Message);
                    }
                }
                NavigationContext.QueryString.TryGetValue("sensortype", out sensorType);
                if ((!string.IsNullOrWhiteSpace(tbEMailAddress.Text)) && (!string.IsNullOrWhiteSpace(tbContent.Text)))
                {
                    buttonSend.IsEnabled = true;
                }
            }
            else
            {
                fromSensorPage = true;
            }
            base.OnNavigatedTo(e);
        }

        private string fileUrl;
        private string sensorType;

        private void buttonSelectEMail_Click(object sender, RoutedEventArgs e)
        {
            var task = new Microsoft.Phone.Tasks.EmailAddressChooserTask();
            task.Completed += new EventHandler<Microsoft.Phone.Tasks.EmailResult>(task_EMailAddrSelectCompleted);
            task.Show();
            fromSensorPage = false;
        }

        void task_EMailAddrSelectCompleted(object sender, Microsoft.Phone.Tasks.EmailResult e)
        {
            if (e.TaskResult == Microsoft.Phone.Tasks.TaskResult.OK)
            {
                tbEMailAddress.Text = e.Email;
                var appSettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                appSettings[emailAddressKey] = e.Email;
                if ((!string.IsNullOrWhiteSpace(tbEMailAddress.Text)) && (!string.IsNullOrWhiteSpace(tbContent.Text)))
                {
                    buttonSend.IsEnabled = true;
                }
            }
        }

        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            var task = new Microsoft.Phone.Tasks.EmailComposeTask();
            task.To = tbEMailAddress.Text;
            task.Subject = sensorType + DateTime.Now.ToString("yyyymmdd_hhMMss");
            string content = tbContent.Text;
            if (!string.IsNullOrWhiteSpace(tbMemo.Text))
            {
                int index = tbContent.Text.IndexOf("<" + sensorType + ">");
                string pre = tbContent.Text.Substring(0, index + sensorType.Length + 2);
                string pos = tbContent.Text.Substring(index + sensorType.Length + 2);
                var builder = new System.Text.StringBuilder();
                builder.Append(pre);
                builder.Append("<memo>" + tbMemo.Text + "</memo>");
                builder.Append(pos);
                content = builder.ToString();
            }
            task.Body = content;
            task.Show();
            fromSensorPage = false;
        }


    }
}